#include <iostream>
#include <cmath>
using namespace std;

int compute_max(int num)
{ // 传入的四位数字需要得到保留，可以int四个变量以此表示从大到小的数，通过循环给这些变量赋值
    int putin_num = num;
    int max_num = 0, second_num = 0, third_num = 0, fourth_num = 0;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > max_num)
        {
            max_num = temp;
        }
        num /= 10;
    }
    num = putin_num;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > second_num && temp < max_num)
        {
            second_num = temp;
        }
        num /= 10;
    }
    num = putin_num;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > third_num && temp < second_num)
        {
            third_num = temp;
        }
        num /= 10;
    }
    num = putin_num;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > fourth_num && temp < third_num)
        {
            fourth_num = temp;
        }
        num /= 10;
    }
    return max_num * 1000 + second_num * 100 + third_num * 10 + fourth_num;
}

int compute_min(int num)
{
    int putin_num = num;
    int max_num = 0, second_num = 0, third_num = 0, fourth_num = 0;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > max_num)
        {
            max_num = temp;
        }
        num /= 10;
    }
    num = putin_num;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > second_num && temp < max_num)
        {
            second_num = temp;
        }
        num /= 10;
    }
    num = putin_num;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > third_num && temp < second_num)
        {
            third_num = temp;
        }
        num /= 10;
    }
    num = putin_num;
    for (int i = 0; i < 4; i++)
    {
        int temp = num % 10;
        if (temp > fourth_num && temp < third_num)
        {
            fourth_num = temp;
        }
        num /= 10;
    }
    return fourth_num * 1000 + third_num * 100 + second_num * 10 + max_num;
}

int func(int num)
{
    int max_num = compute_max(num);
    int min_num = compute_min(num);
    return max_num - min_num;
}

int main()
{
    int n;
    cin >> n;
    // 传进来4位整数

    // func计算4位整数交换数字顺序以后构成的最大值和最小值的差
    while (n != func(n))
    {
        n = func(n);
    }

    cout << n << endl;
    return 0;
}